import { createSlice } from "@reduxjs/toolkit";
import categoryApi from "@/api/product/category";
import {CategoryDataList} from "@/api/product/model/categoryType"

// 创建slice对象
let categorySlice = createSlice({
    // 别名
    name:"category",
    initialState:{
        category1Id:"",
        category2Id:"",
        category3Id:"",
        category1List:[],
        category2List:[],
        category3List:[],
    },
    // reducers
    reducers:{
        // 新增的动作  state 状态值  action 操作对象  {type: , payload: 1}
        // 获取category1List
        getCategory1List:(state, action)=>{
            state.category1List = action.payload
        },
        // 获取category2List
        getCategory2List:(state, action)=>{
            state.category2List = []
            state.category1Id = action.payload.category2Id
            state.category2List = action.payload.res
        },
        // 获取category3List
        getCategory3List:(state, action)=>{
            state.category2List = []
            state.category3List = []
            state.category2Id = action.payload.category3Id
            state.category3List = action.payload.res
        },
        setCategory3Id:(state, action)=>{
            state.category3Id = action.payload
        }
    }
})

export let {getCategory1List,getCategory2List,getCategory3List,setCategory3Id} = categorySlice.actions;

// 声明一个函数
export let asyncGetCategory1List = ()=>{
    return async(dispatch : any) =>{
        try {
            let res = await categoryApi.getCategory1();
            dispatch(getCategory1List(res))
        } catch (error) {
            return Promise.reject(new Error("请求获取失败"))
        }
    }
}
// 声明一个函数
export let asyncGetCategory2List = (category2Id : number)=>{
    
    return async(dispatch : any) =>{
        let res = await categoryApi.getCategory2(category2Id);
        dispatch(getCategory2List({res,category2Id}))
    }
}
// 声明一个函数
export let asyncGetCategory3List = (category3Id : number)=>{
    return async(dispatch : any) =>{
        let res = await categoryApi.getCategory3(category3Id);
        dispatch(getCategory3List({res,category3Id}))
    }
}

export default categorySlice.reducer;